import type { cartDataType } from '@/types/component'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useShoppingCartStore = defineStore(
  'shoppingCart',
  () => {
    /**
     * @param shoppingCartInfo 购物车数组
     */
    const shoppingCartInfo = ref<cartDataType[]>([])
    /**
     *
     * @param setShoppingCartInfo 保存购物车信息，
     */
    const setShoppingCartInfo = (val: cartDataType) => {
      console.log('setShoppingCartInfo')
      const flag = shoppingCartInfo.value.some((item) => item.packageId === val.packageId)
      if (flag) {
        shoppingCartInfo.value.forEach((item) => {
          if (item.packageId === val.packageId && item.inventory > item.count) {
            item.count += val.count
          }
        })
        // console.log(shoppingCartInfo.value)
      } else {
        shoppingCartInfo.value.push(val)
        // console.log(shoppingCartInfo.value)
      }
    }
    /**
     * @param clearShoppingCartInfo 清空购物车信息
     */
    const clearShoppingCartInfo = () => {
      console.log('清空购物车信息')
      shoppingCartInfo.value = []
      uni.removeStorageSync('shoppingCartStore')
    }
    return {
      shoppingCartInfo,
      setShoppingCartInfo,
      clearShoppingCartInfo,
    }
  },
  {
    // 数据持久化
    persist: {
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
